import hashlib
import json
import os
from datetime import datetime
import base64
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad


class LicenseManager:
    def __init__(self):
        self.config_file = 'scorer.dat'  # 改用不那么明显的文件名
        self.max_free_uses = 100
        self._key = hashlib.sha256(b'excel_scorer_2024').digest()  # 固定密钥
        self.load_config()

    def _encrypt_data(self, data: dict) -> bytes:
        """加密数据"""
        # 添加校验和
        data['checksum'] = self._calculate_checksum(data)
        json_data = json.dumps(data)

        iv = get_random_bytes(16)
        cipher = AES.new(self._key, AES.MODE_CBC, iv)
        encrypted_data = cipher.encrypt(pad(json_data.encode(), AES.block_size))

        # 组合IV和加密数据
        return base64.b64encode(iv + encrypted_data)

    def _decrypt_data(self, encrypted_data: bytes) -> dict:
        """解密数据"""
        try:
            raw_data = base64.b64decode(encrypted_data)
            iv = raw_data[:16]
            encrypted = raw_data[16:]

            cipher = AES.new(self._key, AES.MODE_CBC, iv)
            decrypted_data = unpad(cipher.decrypt(encrypted), AES.block_size)
            data = json.loads(decrypted_data)

            # 验证校验和
            stored_checksum = data.pop('checksum', None)
            calculated_checksum = self._calculate_checksum(data)

            if stored_checksum != calculated_checksum:
                raise ValueError("数据被篡改")

            return data
        except Exception:
            return self._get_default_config()

    def _calculate_checksum(self, data: dict) -> str:
        """计算数据校验和"""
        # 移除校验和字段，以免影响计算
        data_copy = data.copy()
        data_copy.pop('checksum', None)

        # 使用固定顺序的键来计算校验和
        sorted_items = sorted(data_copy.items())
        checksum_str = json.dumps(sorted_items) + "excel_scorer_checksum"
        return hashlib.sha256(checksum_str.encode()).hexdigest()

    def _get_default_config(self) -> dict:
        """获取默认配置"""
        return {
            'use_count': 0,
            'license_key': None,
            'machine_id': self.get_machine_id(),
            'install_date': datetime.now().strftime('%Y-%m-%d')
        }

    def load_config(self):
        """加载配置文件"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'rb') as f:
                    encrypted_data = f.read()
                self.config = self._decrypt_data(encrypted_data)
            else:
                self.config = self._get_default_config()
                self.save_config()
        except Exception:
            self.config = self._get_default_config()
            self.save_config()

    def save_config(self):
        """保存配置文件"""
        encrypted_data = self._encrypt_data(self.config)
        with open(self.config_file, 'wb') as f:
            f.write(encrypted_data)

    def get_machine_id(self):
        """获取机器唯一标识"""
        import uuid
        # 增加更多机器特征
        system_info = [
            str(uuid.getnode()),  # MAC地址
            os.getenv('COMPUTERNAME', ''),  # 计算机名
            os.getenv('PROCESSOR_IDENTIFIER', ''),  # CPU信息
            os.getenv('NUMBER_OF_PROCESSORS', '')  # CPU核心数
        ]
        combined_info = ':'.join(system_info)
        return hashlib.sha256(combined_info.encode()).hexdigest()

    def generate_license_key(self, machine_id):
        """生成license key"""
        # 使用更复杂的算法生成license
        key_parts = [
            machine_id,
            'excel_scorer_premium',
            datetime.now().strftime('%Y'),
            self._key.hex()[:8]
        ]
        key_string = ':'.join(key_parts)
        return hashlib.sha256(key_string.encode()).hexdigest()

    def verify_license(self, license_key):
        """验证license key"""
        expected_key = self.generate_license_key(self.config['machine_id'])
        return license_key == expected_key and self._verify_installation()

    def _verify_installation(self) -> bool:
        """验证安装的完整性"""
        current_machine_id = self.get_machine_id()
        return current_machine_id == self.config['machine_id']

    def check_license(self):
        """检查license状态"""
        if self.config['license_key']:
            if self.verify_license(self.config['license_key']):
                return True, "已激活"
            return False, "License无效"

        self.config['use_count'] += 1
        self.save_config()

        remaining = self.max_free_uses - self.config['use_count']
        if remaining <= 0:
            return False, "免费使用次数已用完，请输入License继续使用"
        return True, f"免费使用剩余次数：{remaining}"

    def activate_license(self, license_key):
        """激活license"""
        if self.verify_license(license_key):
            self.config['license_key'] = license_key
            self.save_config()
            return True, "激活成功！"
        return False, "无效的License Key"
